package com.rednote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rednote.common.UserContextHolder;
import com.rednote.entity.Comments;
import com.rednote.entity.Posts;
import com.rednote.entity.UserLikes;
import com.rednote.mapper.CommentsMapper;
import com.rednote.mapper.PostsMapper;
import com.rednote.mapper.UserLikesMapper;
import com.rednote.service.UserLikesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 用户点赞记录表(UserLikes)服务实现类
 *
 * @author yao suxuan
 * @since 2025-05-24 18:10:29
 */
@Service
public class UserLikesServiceImpl extends ServiceImpl<UserLikesMapper, UserLikes> implements UserLikesService {

    @Autowired
    private UserLikesMapper userLikesMapper;
    @Autowired
    private PostsMapper postsMapper;
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String POST_LIKE_KEY_PREFIX = "post:like:";
    private static final String COMMENT_LIKE_KEY_PREFIX = "comment:like:";
    private static final String POST_LIKE_HISTORY_ZSET = "post:like:history";

    public Boolean getIsLike(Integer targetId, int targetType) {
        int userId = UserContextHolder.getUserId();
        String key = targetType == 0 ? POST_LIKE_KEY_PREFIX + targetId : COMMENT_LIKE_KEY_PREFIX + targetId;

        if (redisTemplate.opsForSet().isMember(key, String.valueOf(userId))) return true;

        // 查询数据库（不写入 redis）
        UserLikes userLikes = userLikesMapper.selectOne(
                new QueryWrapper<UserLikes>().eq("user_id", userId).eq("target_id", targetId).eq("target_type", targetType)
        );

        // 只返回 true，不缓存
        return userLikes != null;
    }

    public int like(Integer targetId, int targetType) {
        //查询帖子或评论是否存在
        if (targetType == 0) {
            Posts post = postsMapper.selectById(targetId);
            if (post == null) {
                throw new RuntimeException("帖子不存在");
            }
        } else {
            Comments comment = commentsMapper.selectById(targetId);
            if (comment == null) {
                throw new RuntimeException("评论不存在");
            }
        }
        int userId = UserContextHolder.getUserId();
        String key = (targetType == 0 ? POST_LIKE_KEY_PREFIX : COMMENT_LIKE_KEY_PREFIX) + targetId;

        if (getIsLike(targetId, targetType)) throw new RuntimeException("已点赞"); // 已点赞不重复插入

        UserLikes like = new UserLikes();
        like.setUserId(userId);
        like.setTargetId(targetId);
        like.setTargetType(targetType);
        userLikesMapper.insert(like);

        redisTemplate.opsForSet().add(key, String.valueOf(userId));
        //更新点赞量
        String countKey = (targetType == 0 ? "post:like:count:" : "comment:like:count:") + targetId;
        redisTemplate.opsForValue().increment(countKey, 1);
        //记录帖子id为脏帖
        if(targetType==0) {
            redisTemplate.opsForSet().add("reaction:dirty_posts", String.valueOf(targetId));
            // 新增：记录点赞行为用于推荐
            long timestamp = System.currentTimeMillis();
            redisTemplate.opsForZSet().incrementScore("hot:all", String.valueOf(targetId), 1);
            redisTemplate.opsForZSet().add(POST_LIKE_HISTORY_ZSET, userId + ":" + targetId, timestamp);
        }
        else redisTemplate.opsForSet().add("reaction:dirty_comments", String.valueOf(targetId));
        return getLikeCount(targetId, targetType);
    }

    public int unlike(Integer targetId, int targetType) {
        //查询帖子或评论是否存在
        if (targetType == 0) {
            Posts post = postsMapper.selectById(targetId);
            if (post == null) {
                throw new RuntimeException("帖子不存在");
            }
        } else {
            Comments comment = commentsMapper.selectById(targetId);
            if (comment == null) {
                throw new RuntimeException("评论不存在");
            }
        }
        int userId = UserContextHolder.getUserId();
        String key = (targetType == 0 ? POST_LIKE_KEY_PREFIX : COMMENT_LIKE_KEY_PREFIX) + targetId;
        if (!getIsLike(targetId, targetType)) throw new RuntimeException("未点赞");;
        userLikesMapper.delete(
                new QueryWrapper<UserLikes>().eq("user_id", userId).eq("target_id", targetId).eq("target_type", targetType)
        );
        redisTemplate.opsForSet().remove(key, String.valueOf(userId));
        //更新点赞量
        String countKey = (targetType == 0 ? "post:like:count:" : "comment:like:count:") + targetId;
        redisTemplate.opsForValue().increment(countKey, -1);
        //记录帖子id为脏帖
        if(targetType==0)
            redisTemplate.opsForSet().add("reaction:dirty_posts", String.valueOf(targetId));
        else redisTemplate.opsForSet().add("reaction:dirty_comments", String.valueOf(targetId));
        return getLikeCount(targetId, targetType);
    }
    public Integer getLikeCount(Integer targetId, int targetType) {
        String key = (targetType == 0 ? "post:like:count:" : "comment:like:count:") + targetId;

        // 1. 从 Redis 查询
        String countStr = redisTemplate.opsForValue().get(key);
        if (StringUtils.hasText(countStr)) {
            try {
                int count = Integer.parseInt(countStr);
                return Math.max(count, 0); // 保证不返回负数
            } catch (NumberFormatException e) {
                // Redis 存了非法值，不管，回数据库查
                System.err.println("Warning: Invalid like count in Redis for key: " + key);
            }
        }

        // 2. Redis 没有，查数据库
        int count = 0;
        if (targetType == 0) {
            Posts post = postsMapper.selectById(targetId);
            count = (post != null && post.getLikeCount() != null) ? post.getLikeCount() : 0;
        } else {
            Comments comment = commentsMapper.selectById(targetId);
            count = (comment != null && comment.getLikeCount() != null) ? comment.getLikeCount() : 0;
        }

        count = Math.max(count, 0); // 数据库也防止返回负数

        // 3. 写入 Redis 缓存，设置1小时过期
        redisTemplate.opsForValue().set(key, Integer.toString(count), 1, TimeUnit.HOURS);

        return count;
    }

}
